package com.briup.srms.project.service.impl;

import java.util.Date;
import java.util.List;

import com.briup.srms.sms.bean.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.briup.srms.project.bean.StudentProject;
import com.briup.srms.project.bean.StudentProjectExample;
import com.briup.srms.project.bean.extend.StudentProjectExtend;
import com.briup.srms.project.dao.StudentProjectMapper;
import com.briup.srms.project.dao.extend.StudentProjectExtendMapper;
import com.briup.srms.project.service.IStudentProjectService;
import com.briup.srms.sms.dao.StudentMapper;
import com.jacky.base.utils.CustomerException;
import com.jacky.base.utils.PageVM;

@Service
public class StudentProjectServiceImpl implements IStudentProjectService {
	
	@Autowired
	private StudentProjectMapper studentProjectMapper;
	@Autowired
	private StudentProjectExtendMapper studentProjectExtendMapper;
	@Autowired
	private StudentMapper studentMapper;
	
	@Override
	public PageVM<StudentProjectExtend> pageQuery(int page,int pageSize, String realname, Long clazzId, String status, Long[] channelIds, String[] stuTypes) {
		List<StudentProjectExtend> list = studentProjectExtendMapper.query(page, pageSize, realname, clazzId, status, channelIds, stuTypes);
		long total = studentProjectExtendMapper.count(realname, clazzId, status, channelIds, stuTypes);
		return new PageVM<StudentProjectExtend>(page, pageSize, total, list);
	}
	
	@Override
	public void selectProject(long studentId, long projectId) {
		// 校验：同一渠道的学生不能重复选题
		Student student = studentMapper.selectByPrimaryKey(studentId);
		if(student == null) {
			throw new CustomerException("学生信息异常");
		}
		Long[] channelIds = new Long[] {student.getChannelId()};
		List<StudentProjectExtend> list = studentProjectExtendMapper.query(1, 10, null, null, null, channelIds, null);
		if(list.size()>0) {
			throw new CustomerException("您中意的题目已经被人选了！");
		}
		// 校验：一个学生只能选题一次
		StudentProject spd = this.queryByStudentId(studentId);
		if(spd!=null) {
			throw new CustomerException("该生已经完成了选题");
		}
		// 选题
		StudentProject sp = new StudentProject();
		sp.setStudentId(studentId);
		sp.setProjectId(projectId);
		sp.setCreateTime(new Date().getTime());
		studentProjectMapper.insert(sp);
	}

	@Override
	public StudentProject queryByStudentId(long studentId) {
		StudentProjectExample example = new StudentProjectExample();
		example.createCriteria().andStudentIdEqualTo(studentId);
		List<StudentProject> list = studentProjectMapper.selectByExample(example);
		if(list.size()>0) {
			return list.get(0);
		} else {
			return null;
		}
	}
}
